#include "ClientNet.h"
#include "../../common/config.h"

namespace NET{
    ClientNet::ClientNet(){

    }

    ClientNet::~ClientNet(){

    }

    void ClientNet::test(){
        std::cout<<"hello im client"<<std::endl;
    }

    void ClientNet::error(std::string errorMsg, int errorCode){
        std::cout<<errorMsg<<std::endl;
        printf("errorCode:%d\r\n", errorCode);
        exit(1);
    }

    void ClientNet::connect(){
        int sockfd, portno, n;
        struct sockaddr_in serv_addr;
        struct hostent *server;

        XIAOO::Config config;
        Json::Value configData = config.readClientConfig();
        //test data
        portno = configData["server"]["port"].asInt();
        const char* ip = configData["server"]["ip"].asString().c_str();
        std::cout << ip << std::endl;
        std::cout << portno << std::endl;
        //test data

        //创建socket
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0){
            error("create socket失败", sockfd);
        }

        //准备connect
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = inet_addr(ip);
        serv_addr.sin_port = htons(portno);
        if(::connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0){
            error("connect socket失败");
        }

        this->connfd = sockfd;
    }

    int ClientNet::sendMsg(std::string msg){
        int n;
        int sendSize;
        sendSize = msg.length() + 1;
        if(sendSize > NET::MAXBUFFER){
            char* str;
            sprintf(str, "发送内容超过buffer， MAXBUFFER=%d, msg.length()=%d", NET::MAXBUFFER, sendSize);
            error(str);
        }
        
        int re = write(this->connfd, (char*)msg.c_str(), sendSize);
        if(re > 0){
            // 发送失败
            return re;
        }
        

        // close(this->connfd);

        return 0;
    }

    std::string ClientNet::onRecvMsg(){
        char buffer[NET::MAXBUFFER];

        int n = read(this->connfd, buffer, NET::MAXBUFFER - 1);
        if(n < 0){
            error("read socket失败", n);
        }else if(n == 0){
            error("read socket为空，服务器宕机啦!", n);
        }

        return buffer;
    }
}